package com.york.jobmew.subject.application.interceptor;

import com.york.jobmew.subject.common.constants.LoginConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Feign请求拦截器
 * 针对Feign的RPC调用过程中,上下文的LoginId会丢失的问题去做
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {


    /**
     * 拦截逻辑
     *
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        if (Objects.nonNull(request)) {
            String loginId = request.getHeader(LoginConstant.LOGIN_ID);
            if (StringUtils.isNotBlank(loginId)) {
                requestTemplate.header(LoginConstant.LOGIN_ID, loginId);
            }
        }
    }

}
